<?php namespace xlx;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
use \Workerman\Events\EventInterface;

class Worker 
{ 
    // public function __construct($addr){
    //     $this->addr = $addr;
    // }
    // public function __call($name,$args){

    // }
    // public static function call(){
    //     //发送到service
    // }    
    public static function pipe($addr1,$addr2){
        //发送命令到service：worker接收已经存在的worker终结消息
        //阻塞？？找不到链接进程
    }
    public static function register($addr,$name){
        //发送命令到service: 注册worker唯一名称
        //阻塞？？已经被注册
    }  
    public static function start($opt=[]){ 
        $opt['class'] = static::class;
        if(empty($opt['name'])) $opt['name'] = static::class;
        return Danboo::spawn(function($event,$addr)use($opt){     //阻塞？？返回注册名称     
            yield Danboo::call('register',$opt['name'],$addr);//创建worker 并注册       
            (new $opt['class'])->init($event,$addr,$opt);    
            return $addr;
        });   
        //return new static($addr);
    } 
    public static function start_link($opt=[]){ 
        $opt['class'] = static::class;
        if(empty($opt['name'])) $opt['name'] = static::class; 
        return Danboo::spawn(function($event,$addr)use($opt){  //阻塞？？返回注册名称   
            yield Danboo::call('register',$opt['name'],$addr);//创建worker 并注册 
            yield Danboo::call('link',$opt['name'],$addr); // 链接服务器  
            (new $opt['class'])->init($event,$addr,$opt);     
            return $addr;
        });   
        //return new static($addr);
    }


    public static function supervisor($opt){ 
        //发送命令到service：创建一个supervise并链接一个Worker  
        if(empty($opt['name']))$opt['name'] = static::class; 
        return Danboo::call('supervisor',$opt); //阻塞？？返回注册名称
    }

    public static function pool($opt){
        if(empty($opt['name']))$opt['name'] = static::class; 
        return Danboo::call('pool',$opt); //阻塞？？返回注册名称 
    }

    // public static function worker(){

    //     $server = \stream_socket_client(Danboo::$addr, $errno, $errstr);
    //     $conn = new TcpConnection($socket,$addr);//注册当前进程 

    //     return $addr;
    // }

    public function init($addr){
        //注册后的addr 和 创建配置opt  
    }     
}